﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Tzx.Utilities.Npoi;

namespace Excel2Words
{
    /// <summary>
    /// 
    /// </summary>
    public partial class UcWordExport : UserControl
    {
        #region public

        /// <summary>
        /// 
        /// </summary>
        public UcWordExport()
        {
            InitializeComponent();

            LblReadMeWord.BackColor = AppHelp.Color_Word;
            LblReadMeWord.ForeColor = Color.White;

            Load += UcWordExport_Load;
            BtnSelectWord.Click += BtnSelectWord_Click;
            TxtWordTemplateFile.TextChanged += TxtWordTemplateFile_TextChanged;

            BtnExportFile.Click += BtnExportFile_Click;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="table"></param>
        public void SetExcelTable(DataTable table)
        {
            _excelTable = table;

            FillData();
        }
        private DataTable _excelTable;

        #endregion

        #region 事件方法

        /// <summary>
        /// 导出按钮
        /// </summary>
        void BtnExportFile_Click(object sender, EventArgs e)
        {
            progressExport.Value = progressExport.Minimum;
            try
            {
                BtnExportFile.Enabled = false;
                
                GoExport();
            }
            finally
            {
                BtnExportFile.Enabled = true;
            }
        }

        /// <summary>
        /// 选定Word文件变化时
        /// </summary>
        void TxtWordTemplateFile_TextChanged(object sender, EventArgs e)
        {
            string file = TxtWordTemplateFile.Text = TxtWordTemplateFile.Text.Trim();
            if (file.Length > 0)
            {
                //bool ok = LoadExcel(file);
                //if (!ok)
                //{
                //    return;
                //}

                ////显示
                //dataGridView1.DataSource = ExcelTable;

                //触发事件
                //EventHandler handler = ExcelFileChanged;
                //if (handler != null) handler(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// 选择文件按钮
        /// </summary>
        void BtnSelectWord_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Title = "选择Word模板文件";
                ofd.Filter = "Word2007文件(*.docx)|*.docx";
                ofd.InitialDirectory = Application.StartupPath;
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    TxtWordTemplateFile.Text = ofd.FileName;
                }
            }
        }

        /// <summary>
        /// 窗体加载时
        /// </summary>
        void UcWordExport_Load(object sender, EventArgs e)
        {
            //LblReadMeApp.Text = AppHelp.TEXT_Read_App;
            //LblReadMeExcel.Text = AppHelp.TEXT_Read_Excel;
            LblReadMeWord.Text = AppHelp.TEXT_Read_Word;
            //TxtHelp.Text = AppHelp.TEXT_Read_Help;
        }

        /// <summary>
        /// 动态生成的CheckBox的点击选中事件方法
        /// </summary>
        void cb_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            if (cb == null)
            {
                MessageBox.Show("错误",AppHelp.Title,MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                return;
            }

            //
            //bool isChecked = cb.Checked;
            //string column = cb.Tag.ToString();
            
            //清空并重新添加Label
            flowPanel_Word.Controls.Clear();
            HashSet<string> columns = GetSelectedColumns();
            foreach (string col in columns)
            {
                //Word占位符
                string placeholder = String.Format("{0}{1}{2}",
                    AppHelp.RP_BEGIN,
                    col,
                    AppHelp.RP_END
                    );

                Label lbl = new Label();
                lbl.Parent = flowPanel_Word;
                flowPanel_Word.Controls.Add(lbl);
                lbl.Text = placeholder;
                lbl.Tag = placeholder;
                lbl.AutoSize = true;
                lbl.Padding = new Padding(4);
                lbl.Margin = new Padding(4);
                lbl.BorderStyle = BorderStyle.FixedSingle;
                lbl.BackColor = AppHelp.Color_Word;
                lbl.ForeColor = Color.White;
            }
        }

        #endregion

        #region private

        /// <summary>
        /// 填充数据
        /// </summary>
        private void FillData()
        {
            if (_excelTable == null)
            {
                MessageBox.Show("表格数据为空",AppHelp.Title,MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                return;
            }

            #region 填充

            flowPanel_Excel.Controls.Clear();
            CbAllColumns.Items.Clear();
            CbAllColumns.Items.Add("不需要列名");
            CbAllColumns.SelectedIndex = 0;
            foreach (DataColumn col in _excelTable.Columns)
            {
                string colCaption = col.Caption;

                //填充CheckBox
                CheckBox cb = new CheckBox();
                cb.Parent = flowPanel_Excel;
                flowPanel_Excel.Controls.Add(cb);
                cb.Checked = false;
                cb.Text = colCaption;
                cb.Tag = colCaption;
                cb.AutoSize = true;
                cb.BackColor = AppHelp.Color_Excel;
                cb.ForeColor = Color.White;

                //CheckBox事件
                cb.CheckedChanged += cb_CheckedChanged;

                //填充ComboBox下拉列表
                CbAllColumns.Items.Add(colCaption);
            }
            #endregion


        }

        /// <summary>
        /// 选择的列,需要替换的列
        /// </summary>
        /// <returns></returns>
        private HashSet<string> GetSelectedColumns()
        {
            HashSet<string> selected = new HashSet<string>();
            foreach (Control ctl in flowPanel_Excel.Controls)
            {
                CheckBox cb = ctl as CheckBox;
                if (cb != null)
                {
                    if (cb.Checked)
                    {
                        string columnName = cb.Tag.ToString();
                        if (!string.IsNullOrEmpty(columnName))
                        {
                            if (!selected.Contains(columnName))
                            {
                                selected.Add(columnName);
                            }
                        }
                    }
                }
            }//foreach
            return selected;
        }

        /// <summary>
        /// 
        /// </summary>
        private void GoExport()
        {
            //
            string template = TxtWordTemplateFile.Text = TxtWordTemplateFile.Text.Trim();
            if (template.Length == 0)
            {
                MessageBox.Show("模板文件路径为空",AppHelp.Title,MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                return;
            }

            //
            DataTable table = this._excelTable;
            if (table == null || table.Rows.Count == 0)
            {
                MessageBox.Show("没有数据表", AppHelp.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            //替换字段
            HashSet<string> columns = GetSelectedColumns();
            if (columns == null || columns.Count == 0)
            {
                MessageBox.Show("没有选择替换列", AppHelp.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            //标题字段
            string column_filename = CbAllColumns.SelectedItem.ToString();

            //DataTable 转 List<Dict<string,string>>
            Dictionary<string, string> dict_0 = new Dictionary<string, string>();
            foreach (string column in columns)
            {
                if (!dict_0.ContainsKey(column))
                {
                    string key = string.Format("{0}{1}{2}", AppHelp.RP_BEGIN,column,AppHelp.RP_END);
                    dict_0.Add(key, string.Empty);
                }
            }

            //
            NpoiDocxExport export = new NpoiDocxExport();
            export.DocxTemplateFile = TxtWordTemplateFile.Text;//模板文件
            //export.ReplaceDictList = list;//数据列表
            export.DataTable_ReplaceExport = table;//数据列表
            export.Columns_Replace = columns;
            export.PlaceHolder_Begin = AppHelp.RP_BEGIN;
            export.PlaceHolder_End = AppHelp.RP_END;
            export.FolderName = DateTime.Now.ToString("yyyyMMddHHmmss");
            export.Column_FileName = column_filename;
            export.OnExportProcess += export_ExportProcess;

            //
            string message;
            bool isOpen = false;
            bool ok = export.Export(out message);
            if (ok)
            {
                isOpen = true;
                MessageBox.Show("导出完成,确定打开文件夹",AppHelp.Title,MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            else
            {
                DialogResult dr = MessageBox.Show("导出失败,需要打开导出目录查看吗?\n\n" + message, AppHelp.Title, MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    isOpen = true;
                }
            }

            //
            if (isOpen)
            {
                string path = string.Format("{0}", export.FolderName);
                Process.Start(path);
            }
        }

        void export_ExportProcess(object sender, EventArgs e)
        {
            Application.DoEvents();

            NpoiDocxExportProgressEventArgs e2 = e as NpoiDocxExportProgressEventArgs;
            if (e2 != null)
            {
                //
                int current = e2.CurrentValue;
                int count = e2.CountValue;

                //LogFile.Me.LogText("current=", current.ToString(), "count=", count.ToString());

                //方法2(无进度值)
                if (count <= 0)
                {
                    ExportProcess2_NoValue();
                    return;
                }

                //方法1,进度当前值/进度总值=min/max
                decimal dCurrent = ((decimal) current*(decimal) progressExport.Maximum)/(decimal) count;
                progressExport.Value = (int)dCurrent;
            }

            Application.DoEvents();
        }

        private void ExportProcess2_NoValue()
        {
            progressExport.Value += 1;
            if (progressExport.Value >= progressExport.Maximum)
            {
                progressExport.Value = progressExport.Minimum;
            }
        }

        #endregion

    }
}